package org.ziegler.log.analysis.resultHandler;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import org.ziegler.log.analysis.ConstUtils;
import org.ziegler.log.analysis.LogCore;
import org.ziegler.log.analysis.core.FileUtils;
import org.ziegler.log.analysis.core.SplitColumn;

public class CacheErrResultHandler implements ResultHandler {

    /** 每个Error只有日期最近的一条 */
    private final Map<String, SplitColumn> distinctError = new HashMap<>();

    private final Map<String, Integer> errCount = new HashMap<>();

    /** 已经缓存的Error日志key */
    private final HashSet<String> allCacheErrorKey;

    private final boolean cache;

    public CacheErrResultHandler(boolean cache) {
        this.cache = cache;
        final List<String> errorKeyList = FileUtils.readLines(ConstUtils.CACHE_ALL_ERROR_KEY);
        allCacheErrorKey = new HashSet<>(errorKeyList);
        assert allCacheErrorKey.size() == errorKeyList.size() : "存在重复的ErrorKey";
    }

    @Override
    public void addResult(SplitColumn splitColumn) {
        final String key = splitColumn.getKey();
        if (StringUtils.isNotBlank(key)) {
            if (allCacheErrorKey.contains(key)) {
                // 缓存过的key不在记录
                return ;
            }

            // 只保存不重复的数据
            distinctError.merge(key, splitColumn, (oldValue, newValue) -> {
                if (newValue.getDateTime().isAfter(oldValue.getDateTime())) {
                    // 新Error覆盖旧Error
                    return newValue;
                } else {
                    return oldValue;
                }
            });

            // 记录次数
            int count = errCount.getOrDefault(key, 0);
            errCount.put(key, count + 1);
        }
    }

    @Override
    public void addComplete() {
        if (cache) {
            // 保存缓存
            final Set<String> newErrorKey = distinctError.keySet();
            if (newErrorKey.size() > 0) {
                FileUtils.appendWriteLines(ConstUtils.CACHE_ALL_ERROR_KEY, newErrorKey);
                System.out.println("缓存" + ConstUtils.CACHE_ALL_ERROR_KEY + "，总条目 = " + newErrorKey.size());
            }
        }
    }

    @Override
    public void output() {
        LogCore.info("新增ErrorKey数量 = " + distinctError.size());
        distinctError.forEach((key, value) -> {
            int count = errCount.getOrDefault(key, 0);

            final String s = new StringBuilder().append("[").append(value.getFileName()).append(":").append(count)
                    .append("]").append(value.getStr()).toString();
            LogCore.log(s);
            FileUtils.appendWriteLines(ConstUtils.ONLY_NEW_ERROR, List.of(s));
        });
    }

}
